#include "webSocketServerWidget.h"
#include "ui_webSocketServerWidget.h"
#include <QDateTime>
#include <QNetworkInterface>

webSocketServerWidget::webSocketServerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::webSocketServerWidget)
{
    ui->setupUi(this);
    setWindowTitle("WebSocket服务端");

    ui->pushButton_listen->setEnabled(true);
    ui->pushButton_stop->setEnabled(false);
    ui->pushButton_send->setEnabled(false);

    _pWebSocketServerManager = new WebSocketServerManager("Test");
    connect(_pWebSocketServerManager, SIGNAL(signal_conncted(QString,qint32)),
            this                    , SLOT(slot_conncted(QString,qint32)));
    connect(_pWebSocketServerManager, SIGNAL(signal_disconncted(QString,qint32)),
            this                    , SLOT(slot_disconncted(QString,qint32)));
    connect(_pWebSocketServerManager, SIGNAL(signal_error(QString,quint32,QString)),
            this                    , SLOT(slot_error(QString,quint32,QString)));
    connect(_pWebSocketServerManager, SIGNAL(signal_textFrameReceived(QString,quint32,QString,bool)),
            this                    , SLOT(slot_textFrameReceived(QString,quint32,QString,bool)));
    connect(_pWebSocketServerManager, SIGNAL(signal_textMessageReceived(QString,quint32,QString)),
            this                    , SLOT(slot_textMessageReceived(QString,quint32,QString)));

    ui->lineEdit_ip->setText(getLocalIp());
}

webSocketServerWidget::~webSocketServerWidget()
{
    delete ui;
}

void webSocketServerWidget::slot_conncted(QString ip, qint32 port)
{
    _strList << QString("%1-%2").arg(ip).arg(port);
    _hashIpPort2Message.insert(QString("%1-%2").arg(ip).arg(port), QString());
    _model.setStringList(_strList);
    ui->listView_ipPort->setModel(&_model);
    if(_strList.size() == 1)
    {
        ui->listView_ipPort->setCurrentIndex(_model.index(0));
    }
}

void webSocketServerWidget::slot_disconncted(QString ip, qint32 port)
{
    QString str = QString("%1-%2").arg(ip).arg(port);
    if(_strList.contains(str))
    {
        _strList.removeOne(str);
        _model.setStringList(_strList);
        ui->listView_ipPort->setModel(&_model);
        updateTextEdit();
    }
}

void webSocketServerWidget::slot_sendTextMessageResult(QString ip, quint32 port, bool result)
{
}

void webSocketServerWidget::slot_sendBinaryMessageResult(QString ip, quint32 port, bool result)
{

}

void webSocketServerWidget::slot_error(QString ip, quint32 port, QString errorString)
{

}

void webSocketServerWidget::slot_textFrameReceived(QString ip, quint32 port, QString frame, bool isLastFrame)
{
    if(_hashIpPort2Message.contains(QString("%1-%2").arg(ip).arg(port)))
    {
        _hashIpPort2Message[QString("%1-%2").arg(ip).arg(port)]
                = _hashIpPort2Message[QString("%1-%2").arg(ip).arg(port)] +
                  (_hashIpPort2Message[QString("%1-%2").arg(ip).arg(port)].size() == 0 ? "" :"\n") +
                  QDateTime::currentDateTime().toString("yyyy-HH-mm hh:MM:ss:zzz") + "\n" + frame;
    }
    updateTextEdit();
}

void webSocketServerWidget::slot_textMessageReceived(QString ip, quint32 port, QString message)
{
    qDebug() << __FILE__ << __LINE__ << message;
    if(_hashIpPort2Message.contains(QString("%1-%2").arg(ip).arg(port)))
    {
        _hashIpPort2Message[QString("%1-%2").arg(ip).arg(port)]
                = _hashIpPort2Message[QString("%1-%2").arg(ip).arg(port)] +
                  (_hashIpPort2Message[QString("%1-%2").arg(ip).arg(port)].size() == 0 ? "" :"\n") +
                  QDateTime::currentDateTime().toString("yyyy-HH-mm hh:MM:ss:zzz") + "\n" + message;
    }
    updateTextEdit();
}

void webSocketServerWidget::slot_close()
{
    _pWebSocketServerManager->slot_stop();
    _strList.clear();
    _model.setStringList(_strList);
    ui->listView_ipPort->setModel(&_model);
    ui->textEdit_recv->clear();
}

void webSocketServerWidget::updateTextEdit()
{
    int row = ui->listView_ipPort->currentIndex().row();
    if(row < 0)
    {
        ui->textEdit_recv->setText("");
        return;
    }
    if(_hashIpPort2Message.contains(_strList.at(row)))
    {
        ui->textEdit_recv->setText(_hashIpPort2Message.value(_strList.at(row)));
    }
}

QString webSocketServerWidget::getLocalIp()
{
    QString localIp;
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    for(int index = 0; index < list.size(); index++)
    {
        if(list.at(index).protocol() == QAbstractSocket::IPv4Protocol)
        {
            //IPv4地址
            if (list.at(index).toString().contains("127.0."))
            {
                continue;
            }
            localIp = list.at(index).toString();
            break;
        }
    }
    return localIp;
}

void webSocketServerWidget::on_pushButton_listen_clicked()
{
    _pWebSocketServerManager->slot_start(QHostAddress::Any, ui->spinBox->value());
    ui->pushButton_listen->setEnabled(false);
    ui->pushButton_stop->setEnabled(true);
    ui->pushButton_send->setEnabled(true);
}

void webSocketServerWidget::on_pushButton_stop_clicked()
{
    _pWebSocketServerManager->slot_stop();
    ui->pushButton_listen->setEnabled(true);
    ui->pushButton_stop->setEnabled(false);
    ui->pushButton_send->setEnabled(false);
}

void webSocketServerWidget::on_listView_ipPort_clicked(const QModelIndex &index)
{
    updateTextEdit();
}

void webSocketServerWidget::on_pushButton_send_clicked()
{
    int row = ui->listView_ipPort->currentIndex().row();
    if(_hashIpPort2Message.contains(_strList.at(row)))
    {
        QString str = _strList.at(row);
        QStringList strlist = str.split("-");
        if(strlist.size() == 2)
        {
            _pWebSocketServerManager->slot_sendData(strlist.at(0),
                                                    strlist.at(1).toInt(),
                                                    ui->textEdit_send->toPlainText());
        }
    }
}
